import './OptionsModel.scss'

import { v4 } from 'uuid'
import { useRequest } from 'alova/client'
import { useEffect, useState } from 'react'
import { useEventEmitter, useMount } from 'ahooks'
import { App, Result, Button, Transfer, Tree, Skeleton, Table, Image } from 'antd'
import { FilePreviewSwiper } from '../../Page/Other/Swiper'

import { addAttr } from '../../Utils'

import TreeList, {
    Column,
    HeaderFilter,
    SearchPanel,
    Selection,
} from 'devextreme-react/tree-list';

import {
    DataGrid,
    Lookup,
    Scrolling,
    FilterRow,
    GroupPanel,
    Grouping,
    ColumnFixing,
    Summary,
    GroupItem,
    TotalItem,
    Sorting,
    RowDragging,
    Export,
    LoadPanel,
    ColumnChooser,
    ColumnChooserSearch,
    ColumnChooserSelection,
    Position,
    Paging,
    Pager,
    Search
} from 'devextreme-react/data-grid';


import ExcelData from './ExcelData'

import { Http } from '../../Utils/Api'
import { strOfurlParamsFunc, getFileTypeFromUrl } from '../../Utils'
import { GetSortField } from '../../Utils/DndKit'
import { MappingData } from '../../Config/MappingData'
import { FormTempMapping } from '../../Utils/FormTemp'

import { VideoTempA02 } from '../../Utils/VideoTemp'




const FlowMenuAPIFieldJugdeValue = ['RADIO', 'SELECT', 'SELECTM', 'TREE', 'TREEM', 'CASCADER', 'RADIOLIST', 'CHECKBOXLIST']


// Todo 穿梭框搭配函数
var __rest =
    (this && this.__rest) || function (s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === 'function')
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }

const filterOption = (input, item) => {
    for (const key in item) {
        if (item.hasOwnProperty(key)) {
            const value = item[key]
            if (typeof value === 'string' && value.includes(input)) return true;
        }
    }
    return false
}
// 树形穿梭框
const isChecked = (selectedKeys, eventKey) => selectedKeys.includes(eventKey)
const generateTree = (treeNodes = [], checkedKeys = []) =>
    treeNodes.map(_a => {
        var { children } = _a, props = __rest(_a, ['children'])
        return Object.assign(Object.assign({}, props), { disabled: checkedKeys.includes(props.uuid), children: generateTree(children, checkedKeys) })
    })
const TreeTransfer = _a => {
    var { dataSource, targetKeys = [] } = _a, restProps = __rest(_a, ['dataSource', 'targetKeys'])
    const transferDataSource = []
    function flatten(list = []) {
        list.forEach(item => {
            transferDataSource.push(item)
            flatten(item.children)
        });
    }
    flatten(dataSource)
    return (
        <Transfer
            {...restProps}
            titles={['可选', '已选']}
            targetKeys={targetKeys}
            dataSource={transferDataSource}
            className="tree-transfer"
            render={item => item.tableName}
            showSelectAll={false}
            rowKey={(record) => record.uuid}
        >
            {({ direction, onItemSelect, selectedKeys }) => {
                if (direction === 'left') {
                    const checkedKeys = [...selectedKeys, ...targetKeys]
                    return (
                        <Tree
                            blockNode
                            checkable
                            checkStrictly
                            defaultExpandAll
                            checkedKeys={checkedKeys}
                            treeData={generateTree(dataSource, targetKeys)}
                            fieldNames={{ key: 'uuid', title: 'tableName' }}
                            onCheck={(_, { node: { key } }) => onItemSelect(key, !isChecked(checkedKeys, key))}
                            onSelect={(_, { node: { key } }) => onItemSelect(key, !isChecked(checkedKeys, key))}
                        />
                    );
                }
            }}
        </Transfer>
    );
}
// 基础穿梭框
const BaseTransfer = _a => {
    const { dataSource, targetKeys = [] } = _a, restProps = __rest(_a, ['dataSource', 'targetKeys'])

    return (
        <Transfer
            {...restProps}
            showSearch
            titles={['可选', '已选']}
            targetKeys={targetKeys}
            dataSource={dataSource}
            className="baseTransfer"
            render={item => item.tableName}
            showSelectAll={false}
            rowKey={(record) => record.uuid}
        />
    )
}
// 列表穿梭框
const TableTransfer = _a => {
    const { columns } = _a, restProps = __rest(_a, ['Columns']);
    return (
        <Transfer
            showSearch
            showSelectAll={false}
            rowKey={(record) => record.uuid}
            {...restProps}
        >
            {({ filteredItems, onItemSelect, onItemSelectAll, selectedKeys: listSelectedKeys, disabled: listDisabled }) => {
                const rowSelection = {
                    getCheckboxProps: () => ({ disabled: listDisabled }),
                    onChange(selectedRowKeys) { onItemSelectAll(selectedRowKeys, 'replace') },
                    selectedRowKeys: listSelectedKeys
                };
                return (
                    <Table
                        pagination={false}
                        rowSelection={rowSelection}
                        columns={columns}
                        dataSource={filteredItems}
                        style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                        onRow={({ key, disabled: itemDisabled }) => ({
                            onClick: () => {
                                if (itemDisabled || listDisabled) retur
                                onItemSelect(key, !listSelectedKeys.includes(key));
                            }
                        })}
                        scroll={{ x: 200, y: 'calc(50vh - 60px)' }}
                    />
                )
            }}
        </Transfer>
    )
}

const OptionsModel = ({ data, Off }) => {
    const { message, modal, notification } = App.useApp()
    const { menuUuid, row, config, fieldArr, DevEvent, DateEvent, init, ORGUUID, search } = data
    const { type, field } = config


    const { send } = useRequest(data => Http(data), { immediate: false })

    // TODO 全局 - 新增
    if (type === 'A02') {
        const { addParams } = data
        const { addType, field,// 新增方式
            formMethod, formUrl, formParams, // Form新增
            excelGetMethod, excelGetUrl, excelGetParams, excelSaveMethod, excelSaveUrl, excelSaveParams, // excel添加
            isData, dataKey
        } = config

        const ADDEvent = useEventEmitter()
        ADDEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack') {
                const paramsData = {
                    ...data,
                    ...strOfurlParamsFunc(addParams),
                    ...strOfurlParamsFunc(formParams),
                    organizationUuid: ORGUUID
                }
                if (isData) paramsData[dataKey] = menuUuid
                send({ method: formMethod, url: formUrl, params: paramsData }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                }).catch(err => {
                    ADDEvent.emit({ type: 'closeFormLoading' })
                })
            }
        })

        if (addType === 'form') {
            const [formItem, setFormItem] = useState()
            useMount(async () => {
                const newArr = await Promise.all(field.filter(v => v.visible).map(async item => {
                    const { valueType, dataField, caption,
                        mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue, mappingParExtra,
                        tooltipStatus, tooltip,
                        max, fileType, fileSize, urlLink, urlBtn,
                        judge, jugdeField, jugdeValue,
                    } = fieldArr.find(v => v.id === item.id)


                    const obj = { span: 12, formType: valueType, name: dataField, label: item.caption, rules: item.rules }
                    if (tooltipStatus) obj.tooltip = tooltip

                    if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                        if (mappingType === 'DataMapping') {
                            obj.valueEnum = MappingData[mappingData]
                        }
                        if (mappingType === 'ApiMapping') {
                            const api = await send({ method: 'get', url: mappingApi, params: { OrganizationUuid: ORGUUID, ...strOfurlParamsFunc(mappingPar) } })
                            const data = !!mappingParExtra ?
                                addAttr(api.data.list, { label: mappingLable, value: mappingValue, extra: mappingParExtra }) :
                                addAttr(api.data.list, { label: mappingLable, value: mappingValue })
                            obj.valueEnum = data
                        }
                    }

                    if (valueType.includes('UPLOAD')) {
                        obj.max = max
                        obj.fileType = fileType
                        obj.fileSize = fileSize
                    }
                    if (valueType === 'TempInputLink') {
                        obj.urlLink = urlLink
                        obj.urlBtn = urlBtn
                    }
                    if (judge) {
                        obj.jugdeField = jugdeField
                        obj.jugdeValue = jugdeValue.split(',')
                    }
                    return obj
                }))
                setFormItem(newArr)
            })

            return (
                <div className='DataAddTemp'>
                    {formItem && <FormTempMapping formItem={formItem} FORMEVENT={ADDEvent} />}
                </div>
            )
        }

        if (addType === 'excel') {
            const excelData = {
                getMethod: excelGetMethod,
                getUrl: excelGetUrl,
                getParams: excelGetParams,
                saveMethod: excelSaveMethod,
                saveUrl: excelSaveUrl,
                saveParams: excelSaveParams,
                ORGUUID
            }
            return (
                <div className='DataAddTemp'>
                    <ExcelData config={excelData} DateEvent={DateEvent} />
                </div>
            )
        }
    }
    // TODO 全局 - 查询
    if (type === 'A03') {
        const [formItem, setFormItem] = useState()

        const SearchEvent = useEventEmitter()
        SearchEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack' && JSON.stringify(data) !== '{}') {
                DevEvent.emit({ type: 'onSearch', data })
            }
        })

        useMount(async () => {
            const data = await Promise.all(field.map(async item => {
                const { label, value, isSystem, valueType } = item
                if (isSystem) {
                    const oldData = fieldArr.find(v => v.dataField === value)
                    if (oldData) {
                        const { valueType, mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue } = oldData
                        const obj = { span: 12, formType: valueType, name: value, label: label }
                        if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                            if (mappingType === 'DataMapping') {
                                obj.valueEnum = MappingData[mappingData]
                            }
                            if (mappingType === 'ApiMapping') {
                                const api = await send({ method: 'get', url: mappingApi, params: { ...strOfurlParamsFunc(mappingPar) } })
                                obj.valueEnum = api.data.list.map(item => ({ ...item, label: item[mappingLable], value: item[mappingValue] }))
                            }
                        }
                        return obj
                    }
                } else return ({ span: 12, formType: valueType, name: value, label: label })
            }))
            setFormItem(data.filter(v => v))
        })

        return (
            <div className='DataAddTemp'>
                {formItem && <FormTempMapping formItem={formItem} FORMEVENT={SearchEvent} Initial={init} NotLoading />}
            </div>
        )
    }
    // TODO 全局 - 排序
    if (type === 'A04') {
        const [Data, setData] = useState()
        const CallBackFunc = (e) => {
            const { type, data } = e
            const MapReturn = new Map([
                ['onUpdateField', () => setData(data)]
            ])
            const func = MapReturn.get(type)
            return func && func()
        }
        const A04Event = useEventEmitter()
        A04Event.useSubscription(CallBackFunc)

        const onSubmit = () => {
            if (Data) DevEvent.emit({ type: 'onSort', data: Data })
        }

        return (
            <div className='OptionsModelA02'>
                <GetSortField data={init.length === 0 ? field : init} FieldEvent={A04Event} />
                <Button type='primary' onClick={onSubmit}>提交</Button>
            </div>
        )
    }
    // TODO 全局 - 导出
    if (type === 'A06') {
        const excelData = {
            getMethod: config.getMethod,
            getUrl: config.getUrl,
            getParams: config.getParams,
            ORGUUID,
            search
        }

        return (
            <div className='OptionsModelA06'>
                <ExcelData config={excelData} DateEvent={DateEvent} search={search} />
            </div>
        )
    }
    // TODO 全局 - 批操
    if (type === 'A07') {
        const [loading, setLoading] = useState(false)
        const { bulkType, selectText, saveMethod, saveUrl, saveParams, selectArr, selectParams, formArr, saveKey } = config
        if (bulkType === 'confirm') {
            const onDelete = () => {
                setLoading(true)
                send({ method: saveMethod, url: saveUrl, params: init }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                })
            }
            return (
                <div className='OptionsModelA07Model'>
                    <Result
                        status="warning"
                        title={selectText}
                        extra={[
                            <Button type="primary" danger key="delete" loading={loading} onClick={onDelete}>确认</Button>,
                            <Button key="close" loading={loading} onClick={Off}>取消</Button>,
                        ]}
                    />
                </div>
            )
        }
        if (bulkType === 'select') {
            const onSelect = (e) => {
                setLoading(true)
                const params = init.map(item => ({ uuid: item, [selectParams]: e }))
                send({ method: saveMethod, url: saveUrl, params }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                })
            }
            const button = selectArr.map(({ label, value, type, danger }) => {
                return <Button key={value} type={type} danger={danger} loading={loading} onClick={() => onSelect(value)}>{label}</Button>
            })
            return (
                <div className='OptionsModelA07Model'>
                    <Result
                        status="warning"
                        title={selectText}
                        extra={button}
                    />
                </div>
            )
        }
        if (bulkType === 'form') {
            const [formItem, setFormItem] = useState()
            useMount(async () => {
                const newArr = await Promise.all(formArr.map(async item => {
                    const { valueType, dataField, caption, mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue, tooltipStatus, tooltip, } = item

                    const obj = { span: 12, formType: valueType, name: dataField, label: caption }
                    if (tooltipStatus) obj.tooltip = tooltip

                    if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                        if (mappingType === 'DataMapping') {
                            obj.valueEnum = MappingData[mappingData]
                        }
                        if (mappingType === 'ApiMapping') {
                            const api = await send({ method: 'get', url: mappingApi, params: { ...strOfurlParamsFunc(mappingPar) } })
                            obj.valueEnum = api.data.list.filter(v => v.isEnabled === 1).map(item => ({ ...item, label: item[mappingLable], value: item[mappingValue] }))
                        }
                    }
                    return obj
                }))
                setFormItem(newArr)
            })

            const FormEvent = useEventEmitter()
            FormEvent.useSubscription(val => {
                const { type, data } = val
                if (type === 'onFormBack') {
                    const params = { [saveKey]: init, ...data }
                    send({ method: saveMethod, url: saveUrl, params }).then(res => {
                        DateEvent.emit({ type: 'onRefresh' })
                        Off()
                    })
                }
            })
            return (
                <div className='OptionsModelA07Form'>
                    {formItem && <FormTempMapping formItem={formItem} FORMEVENT={FormEvent} />}
                </div>
            )
        }
    }
    // TODO 单行 - 修改
    if (type === 'B01') {
        const { addParams } = data
        const { addType, field,// 修改方式
            formMethod, formUrl, formParams, // Form修改
            excelGetMethod, excelGetUrl, excelGetParams, excelSaveMethod, excelSaveUrl, excelSaveParams, // excel修改
        } = config

        const ADDEvent = useEventEmitter()
        ADDEvent.useSubscription(val => {
            const { type, data } = val
            if (type === 'onFormBack') {
                const paramsData = { ...data, ...strOfurlParamsFunc(formParams), ...strOfurlParamsFunc(addParams), organizationUuid: ORGUUID }
                send({ method: formMethod, url: formUrl, params: paramsData }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                }).catch(err => {
                    ADDEvent.emit({ type: 'closeFormLoading' })
                })
            }
        })

        if (addType === 'form') {
            const [formItem, setFormItem] = useState()
            const FlowMenuAPIFieldJugdeValue = ['RADIO', 'SELECT', 'SELECTM', 'TREE', 'TREEM', 'CASCADER']
            useMount(async () => {
                const newArr = await Promise.all(field.filter(v => v.visible).map(async item => {
                    const {
                        valueType, dataField, caption, tooltipStatus, tooltip,
                        mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue, mappingParExtra,
                        max, fileType, fileSize, urlLink, urlBtn,
                        judge, jugdeField, jugdeValue,
                        ...old
                    } = fieldArr.find(v => v.id === item.id)
                    const obj = { span: 12, formType: valueType, name: dataField, label: item.caption, rules: item.rules }
                    if (tooltipStatus) obj.tooltip = tooltip
                    if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                        if (mappingType === 'DataMapping') {
                            obj.valueEnum = MappingData[mappingData]
                        }
                        if (mappingType === 'ApiMapping') {
                            const api = await send({ method: 'get', url: mappingApi, params: { OrganizationUuid: ORGUUID, ...strOfurlParamsFunc(mappingPar) } })
                            const data = !!mappingParExtra ?
                                addAttr(api.data.list, { label: mappingLable, value: mappingValue, extra: mappingParExtra }) :
                                addAttr(api.data.list, { label: mappingLable, value: mappingValue })
                            obj.valueEnum = data
                        }
                    }
                    if (valueType === 'TempInputLink') {
                        obj.urlLink = urlLink
                        obj.urlBtn = urlBtn
                    }
                    if (valueType.includes('UPLOAD')) {
                        obj.max = max
                        obj.fileType = fileType
                        obj.fileSize = fileSize
                    }
                    if (judge) {
                        obj.jugdeField = jugdeField
                        obj.jugdeValue = jugdeValue.split(',')
                    }
                    return obj
                }))
                setFormItem(newArr)
            })

            return (
                <div className='DataAddTemp'>
                    {formItem && <FormTempMapping formItem={formItem} FORMEVENT={ADDEvent} Initial={row.row.data} />}
                </div>
            )
        }

        if (addType === 'excel') {
            return (
                <div className='DataAddTemp'>
                    excel 添加
                </div>
            )
        }
    }
    // TODO 单行 - 新增子级
    if (type === 'B10') {
        const { addParams } = data
        const { parentUuid, field,// 修改方式
            formMethod, formUrl, formParams, // Form修改
        } = config

        const ADDEvent = useEventEmitter()
        ADDEvent.useSubscription(val => {
            const { type, data } = val

            if (type === 'onFormBack') {
                const paramsData = { [parentUuid]: row.row.data.uuid, ...data, ...strOfurlParamsFunc(formParams), ...strOfurlParamsFunc(addParams), organizationUuid: ORGUUID }
                send({ method: formMethod, url: formUrl, params: paramsData }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                }).catch(err => {
                    ADDEvent.emit({ type: 'closeFormLoading' })
                })
            }
        })

        const [formItem, setFormItem] = useState()
        const FlowMenuAPIFieldJugdeValue = ['RADIO', 'SELECT', 'SELECTM', 'TREE', 'TREEM', 'CASCADER']
        useMount(async () => {
            const newArr = await Promise.all(field.filter(v => v.visible).map(async item => {
                const {
                    valueType, dataField, caption, tooltipStatus, tooltip,
                    mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue,
                    max, fileType, fileSize,
                    judge, jugdeField, jugdeValue,
                    ...old
                } = fieldArr.find(v => v.id === item.id)
                const obj = { span: 12, formType: valueType, name: dataField, label: item.caption, rules: item.rules }
                if (tooltipStatus) obj.tooltip = tooltip
                if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                    if (mappingType === 'DataMapping') {
                        obj.valueEnum = MappingData[mappingData]
                    }
                    if (mappingType === 'ApiMapping') {
                        const api = await send({ method: 'get', url: mappingApi, params: { ...strOfurlParamsFunc(mappingPar) } })
                        obj.valueEnum = api.data.list.filter(v => v.isEnabled === 1).map(item => ({ ...item, label: item[mappingLable], value: item[mappingValue] }))
                    }
                }

                if (valueType.includes('UPLOAD')) {
                    obj.max = max
                    obj.fileType = fileType
                    obj.fileSize = fileSize
                }
                if (judge) {
                    obj.jugdeField = jugdeField
                    obj.jugdeValue = jugdeValue.split(',')
                }
                return obj
            }))
            setFormItem(newArr)
        })

        return (
            <div className='DataAddTemp'>
                {formItem && <FormTempMapping formItem={formItem} FORMEVENT={ADDEvent} />}
            </div>
        )

    }
    // TODO 单行 - 删除
    if (type === 'B02') {
        const [Loading, setLoading] = useState(false)
        const { deleteText, formMethod, formUrl, formParams } = config
        const onDelete = () => {
            setLoading(true)
            send({ method: formMethod, url: formUrl, params: { uuid: row.row.data.uuid } }).then(() => {
                DateEvent.emit({ type: 'onRefresh' })
                Off()
            })
        }
        return (
            <Result
                status="warning"
                title={deleteText || '删除警告!'}
                extra={[
                    <Button key="A01" style={{ width: 160 }} onClick={Off} loading={Loading}>取消</Button>,
                    <Button key="A02" style={{ width: 160 }} type="primary" danger loading={Loading} onClick={onDelete}>删除</Button>
                ]}
            />
        )
    }

    if (type === 'B04') {
        return (
            <div className='OptionsModelB04'>
                <ExcelData config={config} data={row.row.data} DateEvent={DateEvent} />
            </div>
        )
    }

    // TODO 单行 - 穿梭框
    if (type === 'B07') {
        const { uuid } = row.row.data
        const { transferType, searchArr,
            orgStatus, orgMethod, orgUrl, orgParams, orgMapping, orgJoin, orgKeyValue, orgKey, orgValue,
            leftMethod, leftUrl, leftParams, leftUuid, leftMapping,
            rightMethod, rightUrl, rightParams, rightUuid, rightMapping,
            saveMethod, saveUrl, saveParams, saveSelect, saveUuid, saveMapping
        } = config

        const TransferMapping = {
            base: BaseTransfer,
            tree: TreeTransfer,
            table: TableTransfer
        }

        const [PageStatus, setPageStatus] = useState(false)

        const [LeftAll, setLeftAll] = useState([])
        const [LeftSelect, setLeftSelect] = useState()
        const [LeftTreeData, setLeftTreeData] = useState([])

        const [OptionalData, setOptionalData] = useState([])
        const [SelectedData, setSelectedData] = useState([])

        const getTwoArr = async (OptionalParams, SelectedParams) => {
            const options = await send({ method: leftMethod, url: leftUrl, params: OptionalParams })
            const select = await send({ method: rightMethod, url: rightUrl, params: SelectedParams })
            setOptionalData(options.data.list)
            setSelectedData(select.data.list)
            setPageStatus(true)
        }

        useMount(async () => {
            const OptionalParams = { ...strOfurlParamsFunc(leftParams) }
            const SelectedParams = { ...strOfurlParamsFunc(rightParams) }
            if (orgJoin) OptionalParams.organizationUuid = ORGUUID
            if (leftUuid) OptionalParams[leftMapping] = uuid
            if (rightUuid) SelectedParams[rightMapping] = uuid

            if (orgStatus) {
                const LeftTreeParams = { ...strOfurlParamsFunc(orgParams) }
                const leftData = await send({ method: orgMethod, url: orgUrl, params: LeftTreeParams })
                const { data: { all, defaultvalue, list } } = leftData
                setLeftAll(all)
                setLeftSelect([defaultvalue])
                setLeftTreeData(list)
            } else {
                getTwoArr(OptionalParams, SelectedParams)
            }
        })

        useEffect(() => {
            if (LeftSelect) {
                const OptionalParams = { ...strOfurlParamsFunc(leftParams), [orgMapping]: LeftSelect }
                const SelectedParams = { ...strOfurlParamsFunc(rightParams), [orgMapping]: LeftSelect }
                if (leftUuid) OptionalParams[leftMapping] = uuid
                if (rightUuid) SelectedParams[rightMapping] = uuid
                getTwoArr(OptionalParams, SelectedParams)
            }
        }, [LeftSelect])

        const onSave = () => {
            const params = SelectedData.map(item => {
                let mapping = LeftSelect ? { organizationUuid: LeftSelect[0] } : {}
                if (saveUuid) mapping = { ...mapping, [saveMapping]: uuid }
                return ({ ...strOfurlParamsFunc(saveParams), [saveSelect]: item, ...mapping })
            })
            send({ method: saveMethod, url: saveUrl, params }).then(() => {
                notification.success({ message: '保存成功!', description: '数据保存成功!' })
            })
        }

        const Template = TransferMapping[transferType]

        const onLeftSelect = e => {
            if (e.length === 0) return false
            setLeftSelect(e)
        }

        if (PageStatus) {
            return (
                <div className='OptionsModelB07Box'>
                    {orgStatus &&
                        <div className='LeftList'>
                            <Tree
                                className='TreeBox'
                                blockNode
                                treeData={LeftTreeData}
                                selectedKeys={LeftSelect}
                                expandedKeys={LeftAll}
                                onExpand={setLeftAll}
                                onSelect={onLeftSelect}
                                fieldNames={orgKeyValue ? { key: orgKey, title: orgValue } : { key: 'value', title: 'label' }}
                            />
                        </div>
                    }
                    <div className='OptionsModelB07'>
                        <Template
                            filterOption={filterOption}
                            dataSource={OptionalData}
                            columns={searchArr || []}
                            targetKeys={SelectedData}
                            onChange={setSelectedData}
                        />
                        <Button type='primary' onClick={onSave}>保存数据</Button>
                    </div>
                </div>
            )
        } else return (<Skeleton active paragraph={{ rows: 24 }} />)
    }

    // TODO 单行 - 执行函数
    if (type === 'B08') {
        const { B08Type } = config
        if (B08Type === 'B01') {
            const { uuid } = row.row.data
            const [TreeData, setTreeData] = useState()
            const [Selected, setSelected] = useState()
            const [Loading, setLoading] = useState(false)

            useMount(() => {
                send({ method: 'get', url: 'roleMenu/GetRoleMenuDetailByUserUuid', params: { RoleUuid: uuid } })
                    .then(res => setTreeData(res.data.list))
                send({ method: 'get', url: 'roleMenu/GetRoleMenuListByRole', params: { RoleUuid: uuid } })
                    .then(res => setSelected(res.data))
            })

            const onSelectionChanged = e => {
                setSelected(e.selectedRowKeys)
            }

            const onSave = () => {
                setLoading(true)
                const params = Selected.map(item => ({ roleUuid: uuid, menuUuid: item }))

                send({ method: 'post', url: 'roleMenu', params }).then(() => {
                    notification.success({ message: '保存成功!', description: '角色权限已更新!' })
                    Off()
                })
            }

            return (
                <div className='OptionsModelB0801'>
                    <TreeList
                        id="tasks"
                        keyExpr="uuid"
                        itemsExpr="children"
                        dataStructure="tree"
                        dataSource={TreeData}
                        showBorders={true}
                        columnAutoWidth={true}
                        wordWrapEnabled={true}
                        selectedRowKeys={Selected}
                        onSelectionChanged={onSelectionChanged}
                    >
                        <SearchPanel visible={true} width={250} />
                        <HeaderFilter visible={true} />
                        <Selection mode="multiple" />
                        <Column dataField="tableName" caption="名称" alignment='left' />
                        <Column dataField="remark" caption="备注" alignment='right' />
                    </TreeList>

                    <Button type='primary' loading={Loading} onClick={onSave}>保存</Button>
                </div>
            )
        }
        if (B08Type === 'B02') {
            const [Loading, setLoading] = useState(false)
            const { uuid, tableName, fullName } = row.row.data
            const onReset = () => {
                console.log(row.row.data)
                send({ method: 'post', url: 'users/ResetPassword', params: { uuid } }).then(() => {
                    notification.success({ message: '重置成功!', description: `${tableName}-${fullName} 的密码已重置!` })
                    Off()
                })
            }
            return (
                <div className='OptionsModelB0802'>
                    <Result
                        status="warning"
                        title={`重置 ${tableName}-${fullName} 的密码!`}
                        extra={[
                            <Button key="A01" style={{ width: 160 }} onClick={Off} loading={Loading}>取消</Button>,
                            <Button key="A02" style={{ width: 160 }} type="primary" danger loading={Loading} onClick={onReset}>重置</Button>
                        ]}
                    />
                </div>
            )
        }
        if (B08Type === 'B04') {
            const { uuid } = row.row.data
            const [TreeData, setTreeData] = useState()
            const [Selected, setSelected] = useState()
            const [Loading, setLoading] = useState(false)

            useMount(() => {
                send({ method: 'get', url: 'weChatMenu' }).then(res => setTreeData(res.data.list))
                send({ method: 'get', url: 'roleMenu/GetRoleWeChatMenuListByRole', params: { RoleUuid: uuid } })
                    .then(res => setSelected(res.data))
            })

            const onSelectionChanged = e => setSelected(e.selectedRowKeys)


            const onSave = () => {
                setLoading(true)
                const params = Selected.map(item => ({ roleUuid: uuid, wechatMenuUuid: item }))

                send({ method: 'post', url: 'roleMenu/AddRoleWeChatMenuNew', params }).then(() => {
                    notification.success({ message: '保存成功!', description: '角色权限已更新!' })
                    Off()
                })
            }

            return (
                <div className='OptionsModelB0801'>
                    <TreeList
                        id="tasks"
                        keyExpr="uuid"
                        itemsExpr="children"
                        dataStructure="tree"
                        dataSource={TreeData}
                        showBorders={true}
                        columnAutoWidth={true}
                        wordWrapEnabled={true}
                        selectedRowKeys={Selected}
                        onSelectionChanged={onSelectionChanged}
                    >
                        <SearchPanel visible={true} width={250} />
                        <HeaderFilter visible={true} />
                        <Selection mode="multiple" />
                        <Column dataField="tableName" caption="名称" alignment='left' />
                    </TreeList>

                    <Button type='primary' loading={Loading} onClick={onSave}>保存</Button>
                </div>
            )
        }
        // TODO 巡检详情单页
        if (B08Type === 'S01') {

            const statusMapping = {
                'feec6230-42c1-47c8-8d1a-b2da0b5245e7': '#52c41a',
                'd2644374-3c1b-4b47-89aa-78401e2954bf': '#f5222d',
                'f8cbf105-1173-45ca-8cf1-bd32f49df507': '#1677ff',
                '6d940547-fd68-4e40-87c5-8ae39f6e7556': '#13c2c2',
                'cc8f10e8-0087-4be5-b525-be4d437e7dc6': '#faad14',
                'ca60e686-1f7b-49a6-882e-92ce286832bc': '#eb2f96',
            }

            // console.log(row.row.data)
            const { pitfallAttachment, auditStatusUuid, auditStatusName, securityProblemTypeName, problem, limitDays, securityDate, lng, lat, responsibleDepartment,
                createUserName, createTime } = row.row.data
            return (
                <div className='OptionsModelB08S01'>
                    <div className='OptionsModelB08S01__Box'>
                        <div className='Label'>
                            <div>巡检状态</div>
                            <div style={{ color: statusMapping[auditStatusUuid] }}>{auditStatusName}</div>
                        </div>
                        <FilePreviewSwiper data={pitfallAttachment} />
                        <div className='Label'>
                            <div>隐患等级</div>
                            <div>{securityProblemTypeName}</div>
                        </div>
                        <div className='Label'>
                            <div>隐患名称</div>
                            <div>{problem}</div>
                        </div>
                        <div className='Label'>
                            <div>治理时限</div>
                            <div>{limitDays}</div>
                        </div>
                        <div className='Label'>
                            <div>安全日期</div>
                            <div>{securityDate}</div>
                        </div>
                        <div className='Label'>
                            <div>经纬度</div>
                            <div>{lng},{lat}</div>
                        </div>
                        <div className='Label'>
                            <div>责任单位</div>
                            <div>{responsibleDepartment}</div>
                        </div>
                        <div className='Label'>
                            <div>创建人</div>
                            <div>{createUserName}</div>
                        </div>
                        <div className='Label'>
                            <div>创建时间</div>
                            <div>{createTime}</div>
                        </div>
                    </div>
                </div>
            )
        }
        // TODO 整改详情单页
        if (B08Type === 'S02') {
            const { tableName, securityDetailDate, processAttachment, processDescription, resultAttachment, resultDescription,
                description, handling, handlingName, reviewerName, reviewTime } = row.row.data
            const statusMapping = {
                'e9744b20-9487-457d-9e4b-1256bd47025a': '#13c2c2',
                'e70f70c7-1e1a-4906-885a-b20b620cab30': '#1677ff',
                'ccdcfb2b-20ca-4569-905d-0bcc71cdbc98': '#f5222d',
                '65ae3568-f430-4e23-abd8-6429415ef12f': '#52c41a',
            }


            return (
                <div className='OptionsModelB08S01'>
                    <div className='OptionsModelB08S01__Box'>
                        <div className='Label'>
                            <div>整改日期</div>
                            <div>{securityDetailDate}</div>
                        </div>
                        <div className='Label'>
                            <div>整体描述</div>
                            <div>{description}</div>
                        </div>
                        <div className='Label'>
                            <div>过程描述</div>
                            <div>{processDescription}</div>
                        </div>
                        <FilePreviewSwiper data={processAttachment} />
                        <div className='Label'>
                            <div>结果描述</div>
                            <div>{resultDescription}</div>
                        </div>
                        <FilePreviewSwiper data={resultAttachment} />
                        <div className='Label'>
                            <div>整改状态</div>
                            <div style={{ color: statusMapping[handling] }}>{handlingName}</div>

                        </div>
                        <div className='Label'>
                            <div>审核人</div>
                            <div>{reviewerName}</div>
                        </div>
                        <div className='Label'>
                            <div>审核时间</div>
                            <div>{reviewTime}</div>
                        </div>
                    </div>
                </div>
            )
        }
    }

    // TODO 单行 - 打开列表
    if (type === 'B09') {
        const { getMethod, getUrl, getParams, saveMaster, saveField, saveMapping, searchArr, children,
            devType, SelectionMode, FilterRowVisible, allowColumnResizing, showBorders, showRowLines, showColumnLines, rowAlternationEnabled
        } = config

        const topOptions = children?.filter(v => v.options === 'top')
        const rowOptions = children?.filter(v => v.options === 'row')

        console.log('全局操作', topOptions)
        console.log('行内操作', rowOptions)


        const [Data, setData] = useState([])
        const [Loading, setLoading] = useState(true)
        const getData = () => {
            const params = { ...strOfurlParamsFunc(getParams) }
            if (saveMaster) params[saveMapping] = row.row.data[saveField]
            send({ method: getMethod, url: getUrl, params }).then(res => {
                setData(res.data.list)
                setLoading(false)
            })
        }
        const onBtnClick = (data, item) => {
            setLoading(true)
            const params = {}
            if (saveMaster) params[saveMapping] = row.row.data[saveField]
            if (item.saveMaster) params[item.saveMapping] = data[item.saveField]
            send({ method: item.saveMethod, url: item.saveUrl, params }).then(res => {
                getData()
            }).catch(err => {
                console.log('设置失败', err)
            })
        }
        useMount(getData)

        return (
            <div className='OptionsModelB09'>
                {topOptions && topOptions.length !== 0 &&
                    <div className='topOption'>
                        头部操作
                    </div>
                }
                {devType === 'DevExtremeDataGrid' &&
                    <DataGrid
                        id={v4()}
                        width='100%'
                        keyExpr='uuid'
                        // 基础数据
                        dataSource={Data}
                        // 边框线
                        showBorders={showBorders}
                        showRowLines={showRowLines}
                        showColumnLines={showColumnLines}
                        rowAlternationEnabled={rowAlternationEnabled}
                        // 列设置
                        allowColumnResizing={allowColumnResizing}
                        columnResizingMode={true}
                        showColumnHeaders={true}
                    >
                        <FilterRow visible={FilterRowVisible} applyFilter='auto' />
                        <Selection mode={SelectionMode} allowSelectAll={true} selectAllMode={'page'} showCheckBoxesMode={'always'} />
                        {searchArr.map(item =>
                            <Column
                                key={item.dataField}
                                dataField={item.dataField}
                                caption={item.caption}
                                alignment='center'
                            />
                        )}

                        {/* {rowOptions && rowOptions?.length !== 0 &&
                            <Column
                                key='options'
                                dataField='options'
                                caption='操作'
                                alignment='center'
                                fixed={true}
                                fixedPosition='right'
                                cellRender={e => {
                                    return optionsArr.map((item, index) => {
                                        return (
                                            <Button type='link' loading={Loading} key={index} onClick={() => onBtnClick(e.row.data, item)}>
                                                {item.optionName}
                                            </Button>
                                        )
                                    })
                                }}
                            />
                        } */}
                    </DataGrid>
                }
                {devType === 'DevExtremeTreeGrid' && <div>树形表单</div>}

                {/**/}
            </div>
        )
    }
    if (type === 'B13') {
        const [loading, setLoading] = useState(false)
        const { bulkType, selectText, saveMethod, saveUrl, saveParams, selectArr, selectParams, formArr, isData, dataArr } = config

        const apiParams = {}
        if (isData) dataArr.forEach(({ dataKey, dataMap }) => apiParams[dataKey] = row.row.data[dataMap])


        if (bulkType === 'confirm') {
            const onDelete = () => {
                setLoading(true)
                send({ method: saveMethod, url: saveUrl, params: { init, ...strOfurlParamsFunc(saveParams), ...apiParams } }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                })
            }
            return (
                <div className='OptionsModelA07Model'>
                    <Result
                        status="warning"
                        title={selectText}
                        extra={[
                            <Button type="primary" danger key="delete" loading={loading} onClick={onDelete}>确认</Button>,
                            <Button key="close" loading={loading} onClick={Off}>取消</Button>,
                        ]}
                    />
                </div>
            )
        }
        if (bulkType === 'select') {
            const onSelect = (e) => {
                setLoading(true)
                const params = { uuid: row.row.data.uuid, [selectParams]: e, ...strOfurlParamsFunc(saveParams), ...apiParams }
                send({ method: saveMethod, url: saveUrl, params }).then(res => {
                    DateEvent.emit({ type: 'onRefresh' })
                    Off()
                })
            }
            const button = selectArr.map(({ label, value, type, danger }) => {
                return <Button key={value} type={type} danger={danger} loading={loading} onClick={() => onSelect(value)}>{label}</Button>
            })
            return (
                <div className='OptionsModelA07Model'>
                    <Result
                        status="warning"
                        title={selectText}
                        extra={button}
                    />
                </div>
            )
        }
        if (bulkType === 'form') {
            const [formItem, setFormItem] = useState()
            useMount(async () => {
                const newArr = await Promise.all(formArr.map(async item => {
                    const { valueType, dataField, caption, mappingType, mappingData, mappingApi, mappingPar, mappingLable, mappingValue, tooltipStatus, tooltip,
                        judge, jugdeField, jugdeValue, rules
                    } = item

                    const obj = { span: 12, formType: valueType, name: dataField, label: caption, rules }
                    if (tooltipStatus) obj.tooltip = tooltip

                    if (FlowMenuAPIFieldJugdeValue.includes(valueType)) {
                        if (mappingType === 'DataMapping') {
                            obj.valueEnum = MappingData[mappingData]
                        }
                        if (mappingType === 'ApiMapping') {
                            const api = await send({ method: 'get', url: mappingApi, params: { ...strOfurlParamsFunc(mappingPar) } })
                            obj.valueEnum = api.data.list.filter(v => v.isEnabled === 1).map(item => ({ ...item, label: item[mappingLable], value: item[mappingValue] }))
                        }
                    }
                    if (judge) {
                        obj.jugdeField = jugdeField
                        obj.jugdeValue = [jugdeValue]
                    }

                    return obj
                }))
                setFormItem(newArr)
            })

            const FormEvent = useEventEmitter()
            FormEvent.useSubscription(val => {
                const { type, data } = val
                if (type === 'onFormBack') {
                    const params = { uuid: init, ...data, ...strOfurlParamsFunc(saveParams), ...apiParams }
                    send({ method: saveMethod, url: saveUrl, params }).then(res => {
                        DateEvent.emit({ type: 'onRefresh' })
                        Off()
                    })
                }
            })
            return (
                <div className='OptionsModelA07Form'>
                    {formItem && <FormTempMapping formItem={formItem} FORMEVENT={FormEvent} />}
                </div>
            )
        }
    }

    if (type === 'B15') {
        const { data } = row.row
        const { renderArr } = config
        return (
            <div className='OptionsModelB15'>
                {renderArr.map((item, index) => {
                    if (data[item.value]) {
                        return (
                            <div key={index}>
                                <div>{item.label} : </div>
                                {(() => {
                                    if (item.type === 'txt') return <div className='TXT'> {data[item.value]}</div>
                                    else {
                                        return (
                                            <div className='FILE'>
                                                {data[item.value].map(item => {
                                                    const type = getFileTypeFromUrl(item.url)

                                                    if (type === 'image') {
                                                        return (
                                                            <div key={item.uuid}>
                                                                <Image width={'100%'} height={'100%'} src={item.url} />
                                                            </div>
                                                        )
                                                    }
                                                    if (type === 'video') {
                                                        return (
                                                            <div key={item.uuid}>
                                                                <VideoTempA02 url={item.url} />
                                                            </div>
                                                        )
                                                    }
                                                    if (type === 'edge') {
                                                        return (
                                                            <div key={item.uuid} className='EDGE' onClick={() => window.open(item.url)}>
                                                                {item?.originalName || '打开文档'}
                                                            </div>
                                                        )
                                                    }
                                                })}
                                            </div>
                                        )
                                    }
                                })()}

                            </div>
                        )
                    }
                })}
            </div>
        )
    }



    return <div>OptionsModel - {type} - 请联系管理员</div>
};

export default OptionsModel